package com.enation.app.javashop.seller.api.account;

import com.dag.eagleshop.core.account.model.dto.account.AccountDTO;
import com.dag.eagleshop.core.account.model.dto.account.QueryTradeRecordDTO;
import com.dag.eagleshop.core.account.model.dto.bankcard.BankCardDTO;
import com.dag.eagleshop.core.account.model.dto.bankcard.BindBankCardDTO;
import com.dag.eagleshop.core.account.model.dto.bankcard.QueryBankCardDTO;
import com.dag.eagleshop.core.account.model.dto.base.IdDTO;
import com.dag.eagleshop.core.account.model.dto.base.PageDTO;
import com.dag.eagleshop.core.account.model.dto.base.SortField;
import com.dag.eagleshop.core.account.model.dto.base.ViewPage;
import com.dag.eagleshop.core.account.model.dto.withdraw.AddWithdrawAccountDTO;
import com.dag.eagleshop.core.account.model.dto.withdraw.UpdateWithdrawAccountDTO;
import com.dag.eagleshop.core.account.model.enums.AccountTypeEnum;
import com.dag.eagleshop.core.account.model.enums.WithdrawAccountTypeEnum;
import com.dag.eagleshop.core.account.model.vo.*;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.dag.eagleshop.core.account.service.BankCardManager;
import com.dag.eagleshop.core.delivery.model.dto.JsonBean;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.shop.model.dto.ShopBankCardDTO;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.system.model.dos.Regions;
import com.enation.app.javashop.core.system.service.RegionsManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 账户控制器
 * @author 孙建
 */
@Api(description = "账户接口模块")
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private MemberManager memberManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private BankCardManager bankCardManager;
    @Autowired
    private ShopManager shopManager;
    @Autowired
    private RegionsManager regionsManager;


    @GetMapping("/walletIndex")
    @ApiOperation(value = "我的钱包首页")
    public JsonBean walletIndex() {
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询余额账户
        AccountDTO balanceAccountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.MEMBER_MASTER.getIndex());
        AccountVO balanceAccountVO = new AccountVO();
        if(balanceAccountDTO !=null){
            BeanUtils.copyProperties(balanceAccountDTO, balanceAccountVO);
        }

        // 查询保证金账户
        AccountDTO depositAccountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.DEPOSIT.getIndex());
        AccountVO depositAccountVO = new AccountVO();
        if(depositAccountDTO !=null){
            BeanUtils.copyProperties(depositAccountDTO, depositAccountVO);
        }


        // 封装返回值
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("balanceAccount", balanceAccountVO);
        resultMap.put("depositAccount", depositAccountVO);
        return new JsonBean("查询成功", resultMap);
    }


    @ApiOperation(value = "余额账户页面接口", response = JsonBean.class)
    @GetMapping(value = "/balanceIndex")
    public JsonBean balanceIndex(){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询余额账户
        AccountDTO balanceAccountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.MEMBER_MASTER.getIndex());
        AccountVO balanceAccountVO = new AccountVO();
        BeanUtils.copyProperties(balanceAccountDTO, balanceAccountVO);

        // 封装数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("balanceAccount", balanceAccountVO);
        return new JsonBean("查询成功", resultMap);
    }


    @ApiOperation(value = "保证金账户页面接口", response = JsonBean.class)
    @GetMapping(value = "/depositIndex")
    public JsonBean depositIndex(){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询保证金账户
        AccountDTO depositAccountDTO = accountManager.queryByMemberIdAndAccountType(accountMemberId, AccountTypeEnum.DEPOSIT.getIndex());
        AccountVO depositAccountVO = new AccountVO();
        if(depositAccountDTO!=null){
            BeanUtils.copyProperties(depositAccountDTO, depositAccountVO);
        }

        // 封装返回值
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("depositAccount", depositAccountVO);
        return new JsonBean("查询成功", resultMap);
    }


    @ApiOperation(value = "查询交易记录列表")
    @PostMapping(value = "/queryTradeRecordList")
    public JsonBean queryTradeRecordList(@RequestBody PageDTO<QueryTradeRecordDTO> pageDTO){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询交易记录列表
        QueryTradeRecordDTO queryWithdrawBillDTO = pageDTO.getBody();
        queryWithdrawBillDTO.setMemberId(accountMemberId);
        pageDTO.setOrderBys(new SortField[]{ new SortField(true, "create_time") });
        ViewPage viewPage = accountManager.queryTradeRecordList(pageDTO);
        return new JsonBean("查询成功", viewPage);
    }


    @ApiOperation(value = "提交提现账号，例如：支付宝、微信", response = JsonBean.class)
    @PostMapping(value = "/submitWithdrawAccount")
    public JsonBean submitWithdrawAccount(@RequestBody AddWithdrawAccountVO addWithdrawAccountVO){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        AddWithdrawAccountDTO addWithdrawAccountDTO = new AddWithdrawAccountDTO();
        BeanUtils.copyProperties(addWithdrawAccountVO, addWithdrawAccountDTO);
        addWithdrawAccountDTO.setMemberId(accountMemberId);
        addWithdrawAccountDTO.setTypeName(WithdrawAccountTypeEnum.getTextByIndex(addWithdrawAccountDTO.getType()));
        accountManager.addWithdrawAccount(addWithdrawAccountDTO);
        return new JsonBean("提交成功");
    }


    @ApiOperation(value = "修改提现账号，例如：支付宝、微信", response = JsonBean.class)
    @PostMapping(value = "/updateWithdrawAccount")
    public JsonBean updateWithdrawAccount(@RequestBody UpdateWithdrawAccountVO updateWithdrawAccountVO){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        UpdateWithdrawAccountDTO updateWithdrawAccountDTO = new UpdateWithdrawAccountDTO();
        BeanUtils.copyProperties(updateWithdrawAccountVO, updateWithdrawAccountDTO);
        updateWithdrawAccountDTO.setMemberId(accountMemberId);
        updateWithdrawAccountDTO.setTypeName(WithdrawAccountTypeEnum.getTextByIndex(updateWithdrawAccountDTO.getType()));
        accountManager.updateWithdrawAccountById(updateWithdrawAccountDTO);
        return new JsonBean("更新成功");
    }


    @ApiOperation(value = "查询银行卡列表", response = BankCardDTO.class)
    @PostMapping(value = "/queryBankCardList")
    public JsonBean queryBankCardList(){
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        // 查询银行卡列表
        QueryBankCardDTO queryBankCardDTO = new QueryBankCardDTO();
        queryBankCardDTO.setMemberId(accountMemberId);
        PageDTO<QueryBankCardDTO> pageDTO = new PageDTO<>(1, 1000, queryBankCardDTO);
        pageDTO.setOrderBys(new SortField[]{ new SortField(true, "create_time") });
        ViewPage<BankCardDTO> viewPage = bankCardManager.queryList(pageDTO);
        return new JsonBean("查询成功", viewPage.getRecords());
    }


    @ApiOperation(value = "绑定银行卡", response = JsonBean.class)
    @PostMapping(value = "/bindBankCard")
    public JsonBean bindBankCard(@RequestBody BindBankCardVO bindBankCardVO){
        Seller seller = UserContext.getSeller();
        Integer uid = seller.getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        Member member = memberManager.getModel(uid);

        // 绑定银行卡
        BindBankCardDTO bindBankCardDTO = new BindBankCardDTO();
        BeanUtils.copyProperties(bindBankCardVO, bindBankCardDTO);
        bindBankCardDTO.setMemberId(accountMemberId);
        bindBankCardDTO.setMobile(member.getMobile());
        bankCardManager.bind(bindBankCardDTO);

        // 更新shopDetail中银行卡信息
        ShopBankCardDTO shopBankCard = new ShopBankCardDTO();
        shopBankCard.setShopId(seller.getSellerId());
        shopBankCard.setBankName(bindBankCardVO.getBankName());
        shopBankCard.setBankAccountName(bindBankCardVO.getOpenAccountName());
        shopBankCard.setBankNumber(bindBankCardVO.getCardNo());
        // 企业账户设置开户行省市
        Integer bankProvinceId = bindBankCardVO.getBankProvinceId();
        Integer bankCityId = bindBankCardVO.getBankCityId();
        if (bankProvinceId != null && bankCityId != null) {
            this.buildShopBankCard(shopBankCard, bankProvinceId, bankCityId);
        }

        return new JsonBean("绑定成功");
    }

    @ApiOperation(value = "根据id更新银行卡", notes = "根据id更新银行卡")
    @PostMapping(value = "updateBankCard")
    public JsonBean updateById(@RequestBody BankCardVO bankCardVO){
        Seller seller = UserContext.getSeller();
        if (ObjectUtils.isEmpty(seller)) {
            throw new RuntimeException("商户登录异常");
        }
        BankCardDTO bankCardDTO = new BankCardDTO();
        BeanUtil.copyProperties(bankCardVO, bankCardDTO);
        bankCardManager.updateBankCard(bankCardDTO);

        // 更新shopDetail中银行卡信息
        ShopBankCardDTO shopBankCard = new ShopBankCardDTO();
        shopBankCard.setShopId(seller.getSellerId());
        shopBankCard.setBankName(bankCardVO.getBankName());
        shopBankCard.setBankAccountName(bankCardVO.getOpenAccountName());
        shopBankCard.setBankNumber(bankCardVO.getCardNo());
        // 企业账户设置开户行省市
        Integer bankProvinceId = bankCardVO.getBankProvinceId();
        Integer bankCityId = bankCardVO.getBankCityId();
        if (bankProvinceId != null && bankCityId != null) {
            this.buildShopBankCard(shopBankCard, bankProvinceId, bankCityId);
        }
        shopManager.updateBankCard(shopBankCard);
        return new JsonBean("更新成功");
    }

    private void buildShopBankCard(ShopBankCardDTO shopBankCard, Integer bankProvinceId, Integer bankCityId) {
        Regions province = regionsManager.getModel(bankProvinceId);
        Regions city = regionsManager.getModel(bankCityId);
        shopBankCard.setBankProvinceId(bankProvinceId);
        shopBankCard.setBankProvince(province.getLocalName());
        shopBankCard.setBankCityId(bankCityId);
        shopBankCard.setBankCity(city.getLocalName());
    }

    @ApiOperation(value = "解绑银行卡，需短信验证", response = JsonBean.class)
    @PostMapping(value = "/unBindBankCard")
    public JsonBean unBindBankCard(@RequestBody UnBindBankCardVO unBindBankCardVO){
        Seller seller = UserContext.getSeller();
//        Integer uid = seller.getUid();

        // 解绑银行卡
        bankCardManager.unbind(IdDTO.by(unBindBankCardVO.getBankCardId()));
        return new JsonBean("解绑成功");
    }

    /**
     * 获取账户会员id
     */
    private String getAccountMemberId(Integer uid){
        Member member = memberManager.getModel(uid);
        return member.getAccountMemberId();
    }

}
